package cn.w.outdoor.lib.common;

import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.util.Log;

public class CommonVideoCodecMethods {

    private final static String TAG = "VideoCodec";

    /**
     * 查询在指定mimeType下，可用的编码器信息
     *
     * @param mimeType 编码类型
     * @return 可用的编码器信息；null，如果没有可用的编码器
     */
    public static MediaCodecInfo selectCodec(String mimeType) {
        int numCodecs = MediaCodecList.getCodecCount();
        for (int i = 0; i < numCodecs; i++) {
            MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);
            if (!codecInfo.isEncoder()) {
                continue;
            }
            String[] types = codecInfo.getSupportedTypes();
            for (int j = 0; j < types.length; j++) {
                if (types[j].equalsIgnoreCase(mimeType)) {
                    return codecInfo;
                }
            }
        }
        return null;
    }

    public static byte[] swapNV21toNV12(byte[] paramArrayOfByte) {
        for (int i = 2 * paramArrayOfByte.length / 3; ; i = 1 + (i + 1)) {
            if (i >= -1 + paramArrayOfByte.length) {
                return paramArrayOfByte;
            }
            byte j = paramArrayOfByte[i];
            paramArrayOfByte[i] = paramArrayOfByte[(i + 1)];
            paramArrayOfByte[(i + 1)] = j;
        }
    }

    /**
     * Returns true if this is a color format that this test code
     * understands (i.e. we know how to read and generate frames in this
     * format).
     */
    public static boolean isRecognizedFormat(int colorFormat2) {
        switch (colorFormat2) {
            case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar:
            case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedPlanar:
            case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar:
            case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420PackedSemiPlanar:
            case MediaCodecInfo.CodecCapabilities.COLOR_TI_FormatYUV420PackedSemiPlanar:
                return true;
        }
        return false;
    }

    public static int selectColorFormat(MediaCodecInfo codecInfo, String mimeType) {
        MediaCodecInfo.CodecCapabilities capabilities = codecInfo.getCapabilitiesForType(mimeType);
        for (int i = 0; i < capabilities.colorFormats.length; i++) {
            int colorFormat = capabilities.colorFormats[i];
            Log.d(TAG, "Get ColorFormat:" + colorFormat);
            if (isRecognizedFormat(colorFormat)) {
                return colorFormat;
            }
        }
        Log.e(TAG, "couldn't find a good color format for " + codecInfo.getName() + " / " + mimeType);
        return -1; // not reached
    }

}
